package org.crackjack.android.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.crackjack.android.R;
import org.crackjack.android.async.ITaskFinishedHandler;
import org.crackjack.android.async.ProgressDialogAsyncTask;
import org.crackjack.android.model.Appointment;
import org.crackjack.android.util.DeviceUtil;
import org.crackjack.android.util.HttpClient;
import org.crackjack.android.util.Logger;
import org.crackjack.android.util.ResponseJsonParser;
import org.crackjack.android.util.UrlBuilder;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class AuthorizationActivity extends GenericActivity implements OnClickListener {

    public static final String AUTHORIZATION_STATUS = "authorization_status";

    private Button registrationButton;
    private Button authorizationButton;

    private EditText loginEditText;
    private EditText passwordEditText;

    private String json = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_authorization);

        authorizationButton = (Button) findViewById(R.id.button_authorization);
        registrationButton = (Button) findViewById(R.id.button_registration);

        loginEditText = (EditText) findViewById(R.id.edit_text_login);
        passwordEditText = (EditText) findViewById(R.id.edit_text_password);

        authorizationButton.setOnClickListener(this);
        registrationButton.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_authorization:
                if (DeviceUtil.hasInternetConnection(this)) {
                    ITaskFinishedHandler<String> getAppointmentsHandler = new ITaskFinishedHandler<String>() {

                        @Override
                        public void onTaskFinished(String result) {
                            if (result.equals("success")) {
                                ITaskFinishedHandler<List<Appointment>> sendAppointmentsToListHandler = new ITaskFinishedHandler<List<Appointment>>() {

                                    @Override
                                    public void onTaskFinished(List<Appointment> result) {
                                        ArrayList<Appointment> appointmentsArrayList = new ArrayList<Appointment>(
                                                result);

                                        Logger.i(getClass(), "Appointment number: " + appointmentsArrayList.size());
                                        startActivity(AppointmentListActivity.class, "appointments",
                                                appointmentsArrayList);
                                    }
                                };
                                new GetAppointmentsAsyncTask(AuthorizationActivity.this, true, "Get Appointments...",
                                        sendAppointmentsToListHandler).execute();

                            } else {
                                showToast("Authorization error");
                            }
                        }
                    };
                    new AuthorizationAsyncTask(this, true, "Authorization...", getAppointmentsHandler).execute();

                } else {
                    showToast("Need Internet connection");
                }
                break;
            case R.id.button_registration:
                startActivity(RegistrationActivity.class);
                break;
            default:
                break;
        }

    }

    private class AuthorizationAsyncTask extends ProgressDialogAsyncTask<Void, Void, String> {

        public AuthorizationAsyncTask(Activity activity, boolean isProgressBarDialog, String dialogMessage,
                ITaskFinishedHandler<String> handler) {
            super(activity, isProgressBarDialog, dialogMessage, handler);
        }

        @Override
        protected String saveDoInBackground(Void... params) {
            HttpClient client = new HttpClient();
            String authorizationStatus = null;
            try {
                json = client.makeGetRequest(UrlBuilder.buildAuthorizationUrl(loginEditText.getEditableText()
                        .toString(), passwordEditText.getEditableText().toString()));
                authorizationStatus = ResponseJsonParser.parseAuthorizationJson(json);

            } catch (JsonParseException e) {
                AuthorizationActivity.this.showToast("Our Server is Temporarily Unavailable");
            } catch (JsonMappingException e) {
                AuthorizationActivity.this.showToast("Our Server is Temporarily Unavailable");
            } catch (ClientProtocolException e) {
                AuthorizationActivity.this.showToast("Our Server is Temporarily Unavailable");
            } catch (IOException e) {
                AuthorizationActivity.this.showToast("Our Server is Temporarily Unavailable");
            }

            return authorizationStatus;
        }
    }

    private class GetAppointmentsAsyncTask extends ProgressDialogAsyncTask<Void, Void, List<Appointment>> {

        public GetAppointmentsAsyncTask(Activity activity, boolean isProgressBarDialog, String dialogMessage,
                ITaskFinishedHandler<List<Appointment>> handler) {
            super(activity, isProgressBarDialog, dialogMessage, handler);
        }

        @Override
        protected List<Appointment> saveDoInBackground(Void... params) {
            HttpClient client = new HttpClient();
            List<Appointment> appointmentsList = null;
            try {
                json = client.makeGetRequest(UrlBuilder.buildGetAllAppointmentsUrl());
                appointmentsList = ResponseJsonParser.parseAppointmentsJson(json);
            } catch (ClientProtocolException e) {
                AuthorizationActivity.this.showToast("Our Server is Temporarily Unavailable");
            } catch (IOException e) {
                AuthorizationActivity.this.showToast("Our Server is Temporarily Unavailable");
            }

            return appointmentsList;

        }
    }
}
